//
//  PlayVideoViewController.m
//  JiZhuiAn
//
//  Created by Easy.Lin on 16/7/10.
//  Copyright © 2016年 Easy. All rights reserved.
//

#import "PlayVideoViewController.h"
#import "ZXVideoPlayerController.h"

#import "ChangeVideoURLButton.h"

#import "ZXVideo.h"
#import "TrainingVideoData.h"
#import "UILabel+StringFrame.h"

#import <UIImageView+WebCache.h>

@interface PlayVideoViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UIScrollView * scrollView;
@property (nonatomic, strong) UIView * contentView;
@property (nonatomic, assign) NSInteger selectedIndex;
@property (nonatomic, strong) PlayVideoViewModel * viewModel;
@property (nonatomic, strong) UITableView * actionTableView;
@property (nonatomic, strong) ZXVideoPlayerController *videoController;
@property (nonatomic, strong) UILabel * actionDescriptionLabel;
@property (nonatomic, strong) UILabel * actionDescriptionContentLabel;

@end

@implementation PlayVideoViewController
@dynamic viewModel;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.viewModel.targetNode.data.projectDescription;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(backButtonDo)];
}

- (void)viewSetting
{
    [super viewSetting];
    self.view.backgroundColor = [UIColor colorWithRGBHex:0xEDEDF0];
    self.selectedIndex = 0;
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.contentView];
    [self.contentView addSubview:self.actionTableView];
    [self.contentView addSubview:self.actionDescriptionLabel];
    [self.contentView addSubview:self.actionDescriptionContentLabel];
}

- (void)bindViewModel
{
    [super bindViewModel];
    @weakify(self);
    [RACObserve(self.viewModel, targetNode) subscribeNext:^(Node * x) {
        @strongify(self);
        [self.viewModel.loadVideoInfoCommand execute:nil];
    }];
    [[RACObserve(self.viewModel, dataSource) skip:1] subscribeNext:^(NSMutableArray * x) {
        @strongify(self);
        if(x.count == 0)
        {
            [MBProgressHUD showQuickTipWithTitle:@"视频文件数量为0" withText:@"无法播放"];
            [self.navigationController popViewControllerAnimated:YES];
            return ;
        }
        TrainingVideoData * data = x[self.selectedIndex];
        ZXVideo * video = [[ZXVideo alloc] init];
        video.playUrl = data.videoURL;
        [self playVideo];
        self.videoController.video = video;
        self.actionDescriptionContentLabel.text = data.actionDescription;
        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:self.selectedIndex
                                                     inSection:0];
        [self.actionTableView selectRowAtIndexPath:indexPath
                                          animated:NO
                                    scrollPosition:UITableViewScrollPositionNone];
        [self firstMakeConstraints];
    }];
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"fullScreenVideoShowed" object:nil] subscribeNext:^(id x) {
        @strongify(self);
        self.navigationController.navigationBarHidden = YES;
    }];
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"smallScreenVideoShowed" object:nil] subscribeNext:^(id x) {
        @strongify(self);
        self.navigationController.navigationBarHidden = NO;
    }];
}

- (void)makeConstaints
{
    [super makeConstaints];
    WS(weakSelf);
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(@0);
        make.top.equalTo(@(kZXVideoPlayerOriginalHeight));
    }];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(weakSelf.scrollView);
    }];
}

- (void)firstMakeConstraints
{
    WS(weakSelf);
    CGFloat height = [self.actionDescriptionContentLabel boundingRectWithSize:CGSizeMake(screenWidth-20, 0)].height + 10;
    [self.actionTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(screenWidth));
        make.top.equalTo(@(0));
        make.height.equalTo(@(44 * self.viewModel.dataSource.count));
    }];
    [self.actionDescriptionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@10);
        make.top.equalTo(weakSelf.actionTableView.mas_bottom).offset(5);
    }];
    [self.actionDescriptionContentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@10);
        make.right.equalTo(@(-10));
        make.width.equalTo(@(screenWidth-20));
        make.height.equalTo(@(height));
        make.top.equalTo(weakSelf.actionDescriptionLabel.mas_bottom);
    }];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.actionTableView.mas_right);
        make.bottom.equalTo(weakSelf.actionDescriptionContentLabel.mas_bottom).offset(5);
    }];
}

- (void)reMakeConstraints
{
    WS(weakSelf);
    CGFloat height = [self.actionDescriptionContentLabel boundingRectWithSize:CGSizeMake(screenWidth-20, 0)].height + 10;
    [self.actionDescriptionContentLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@10);
        make.right.equalTo(@(-10));
        make.width.equalTo(@(screenWidth-20));
        make.height.equalTo(@(height));
        make.top.equalTo(weakSelf.actionDescriptionLabel.mas_bottom);
    }];
}

- (void)changeURLWithIndex:(NSInteger)index
{
    TrainingVideoData * data = self.viewModel.dataSource[index];
    ZXVideo * video = [[ZXVideo alloc] init];
    video.playUrl = data.videoURL;
    self.videoController.video = video;
    self.actionDescriptionContentLabel.text = data.actionDescription;
    [self reMakeConstraints];
}

- (void)playVideo
{
    if (!self.videoController) {
        self.videoController = [[ZXVideoPlayerController alloc] initWithFrame:CGRectMake(0, 0, kZXVideoPlayerOriginalWidth, kZXVideoPlayerOriginalHeight) needRepeat:YES];
        
        __weak typeof(self) weakSelf = self;
        self.videoController.videoPlayerGoBackBlock = ^{
            __strong typeof(self) strongSelf = weakSelf;
            
            [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
            
            [strongSelf.navigationController popViewControllerAnimated:YES];
            [strongSelf.navigationController setNavigationBarHidden:NO animated:YES];
            
            [[NSUserDefaults standardUserDefaults] setObject:@0 forKey:@"ZXVideoPlayer_DidLockScreen"];
            
            strongSelf.videoController = nil;
        };
        
        self.videoController.videoPlayerWillChangeToOriginalScreenModeBlock = ^(){
            NSLog(@"切换为竖屏模式");
        };
        self.videoController.videoPlayerWillChangeToFullScreenModeBlock = ^(){
            NSLog(@"切换为全屏模式");
        };
        
        [self.videoController showInView:self.view];
    }
}

- (void)backButtonDo
{
    [self.videoController backButtonClick];
}

-(void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    if ([self.actionTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.actionTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.actionTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.actionTableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.videoController backButtonClick];
}

#pragma mark - TableViewDelegate && DataSource
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    //按照作者最后的意思还要加上下面这一段
    
    if([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]){
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.viewModel.dataSource.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identifier = @"Cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(!cell){
        TrainingVideoData * model = self.viewModel.dataSource[indexPath.row];
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
        cell.textLabel.text = model.actionName;
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self changeURLWithIndex:indexPath.row];
}

#pragma mark - Getter
- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
    }
    return _scrollView;
}

- (UIView *)contentView
{
    if (!_contentView) {
        _contentView = [[UIView alloc] init];
    }
    return _contentView;
}

- (UITableView *)actionTableView
{
    if (!_actionTableView) {
        _actionTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _actionTableView.delegate = self;
        _actionTableView.dataSource = self;
    }
    return _actionTableView;
}

- (UILabel *)actionDescriptionLabel
{
    if (!_actionDescriptionLabel) {
        _actionDescriptionLabel = [[UILabel alloc] init];
        _actionDescriptionLabel.text = @"动作要领";
    }
    return _actionDescriptionLabel;
}

- (UILabel *)actionDescriptionContentLabel
{
    if (!_actionDescriptionContentLabel) {
        _actionDescriptionContentLabel = [[UILabel alloc] init];
        _actionDescriptionContentLabel.backgroundColor = [UIColor clearColor];
        _actionDescriptionContentLabel.numberOfLines = 0;
        _actionDescriptionContentLabel.font = [UIFont systemFontOfSize:14.0];
    }
    return _actionDescriptionContentLabel;
}

#pragma mark - LifeCycle
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
